package com.example.terrorsms;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.terrorsms.helper.Utilities;
import com.example.terrorsms.model.EventsDataSource;
import com.example.terrorsms.model.ScheduledEvent;
import com.example.terrorsms.model.SoupMessages;


/*
 * 
 *   _________ 
 *  /         \ 
 * |  0     0  | 
 * |     o     |   Plz be kind to our src.
 * |   \___/   | 
 *  \_________/
 */
@SuppressLint({ "NewApi", "NewApi" })
public class MainActivity extends Activity implements OnClickListener {
	private final static String TAG = "MainActivity";
	private static final int TIME_DIALOG_ID = 999;

	List<String> birthdayMessages = null;
	List<String> xmasMessages = null;
	List<String> sylvesterMessages = null;

	public static int EVENT_TYPE = 0;
	public static final int TYPE_OWN = 0;
	public static final int TYPE_CHRISTMAS = 1;
	public static final int TYPE_NEWYEAREVE = 2;
	public static final int TYPE_BIRTHDAY = 3;

	private Button selectEventTypeButton = null;
	private Button chooseContactsButton = null;
	private Button generateMessage = null;
	private Button cancelButton = null;
	private Button save = null;

	public static final int REQUEST_CODE = 0;

	private int minute;
	private int hourOfDay;
	private int dayOfMonth;
	private int month;
	private int year;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);

		SoupMessages so = new SoupMessages();

		birthdayMessages = so.getBirthdayMessages();
		xmasMessages = so.getXmasMessages();
		sylvesterMessages = so.getSylvesterMessages();

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		selectEventTypeButton = (Button) findViewById(R.id.btnSelectEventType);
		selectEventTypeButton.setOnClickListener(this);

		chooseContactsButton = (Button) findViewById(R.id.btnChooseContacts);
		chooseContactsButton.setOnClickListener(this);

		generateMessage = (Button) findViewById(R.id.btnGenerateMessage);
		generateMessage.setOnClickListener(this);

		cancelButton = (Button) findViewById(R.id.btnCreateEventCancel);
		cancelButton.setOnClickListener(this);

		setCurrentDate();
		save = (Button) findViewById(R.id.btnCreateEventSave);
		save.setOnClickListener(this);

		final OnDateSetListener onDateSetListener = new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker arg0, int year, int month,
					int dayOfMonth) {
				setYear(year);
				setMonth(month);
				setDayOfMonth(dayOfMonth);
				final Button dateButton = (Button) findViewById(R.id.buttonOpenDatePicker);
				dateButton.setText(dayOfMonth + ". " + month + ". " + year);
			}
		};

		final Button dateText = (Button) findViewById(R.id.buttonOpenDatePicker);
		dateText.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Calendar cal = Calendar.getInstance();
				DatePickerDialog datePickDiag = new DatePickerDialog(
						MainActivity.this, onDateSetListener, cal
								.get(Calendar.YEAR), cal.get(Calendar.MONTH),
						cal.get(Calendar.DAY_OF_MONTH));
				datePickDiag.show();
			}
		});
		final Button buttonTimePicker = (Button) findViewById(R.id.buttonCreateEventTime);
		buttonTimePicker.setOnClickListener(new View.OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});
	}

	protected void generateEventMessage() {
		EditText msgText = (EditText) findViewById(R.id.txtCreateEventMessage);
		List<String> messages = null;
		Log.d(TAG, "====> ETYPE = " + EVENT_TYPE);
		switch (EVENT_TYPE) {
		case (TYPE_BIRTHDAY): {
			messages = birthdayMessages;
			break;
		}
		case (TYPE_CHRISTMAS): {
			messages = xmasMessages;
			break;
		}
		case (TYPE_NEWYEAREVE): {
			messages = sylvesterMessages;
			break;
		}
		}
		if (messages != null) {
			int i = (int) (Math.random() * messages.size() + 1);
			String msg = messages.get(i);
			Log.d(TAG, msg);
			msgText.setText(msg);
		}
	}

	private void setCurrentDate() {
		Calendar cal = Calendar.getInstance();
		setYear(cal.get(Calendar.YEAR));
		setMonth(cal.get(Calendar.MONTH));
		setDayOfMonth(cal.get(Calendar.DAY_OF_MONTH));
		setHourOfDay(cal.get(Calendar.HOUR_OF_DAY));
		setMinute(cal.get(Calendar.MINUTE));

		final Button dateText = (Button) findViewById(R.id.buttonOpenDatePicker);
		dateText.setText(dayOfMonth + ". " + month + ". " + year);
		final Button buttonTimePicker = (Button) findViewById(R.id.buttonCreateEventTime);
		buttonTimePicker.setText(new StringBuilder().append(pad(hourOfDay))
				.append(":").append(pad(minute)));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
		}

	}

	private final TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			hourOfDay = selectedHour;
			minute = selectedMinute;

			final Button buttonTimePicker = (Button) findViewById(R.id.buttonCreateEventTime);
			buttonTimePicker.setText(new StringBuilder().append(pad(hourOfDay))
					.append(":").append(pad(minute)));
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			if (0 == hourOfDay && 0 == minute) {
				Calendar cal = Calendar.getInstance();
				hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
				minute = cal.get(Calendar.MINUTE);
			}
			return new TimePickerDialog(this, timePickerListener, hourOfDay,
					minute, false);
		}
		return null;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Wähle einen Typen");
		menu.add(0, v.getId(), 0, "Eigenes Event");
		menu.add(0, v.getId(), 0, "Geburtstag");
		menu.add(0, v.getId(), 0, "Weihnachten");
		menu.add(0, v.getId(), 0, "Sylvester");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getTitle() == "Eigenes Event") {
			((Button) findViewById(R.id.buttonCreateEventTime))
					.setVisibility(TextView.VISIBLE);
			((Button) findViewById(R.id.buttonOpenDatePicker))
					.setVisibility(Button.VISIBLE);
			((TextView) findViewById(R.id.textView3))
					.setVisibility(Button.VISIBLE);
			((TextView) findViewById(R.id.textView4))
					.setVisibility(Button.VISIBLE);
			((Button) findViewById(R.id.btnChooseContacts))
					.setVisibility(Button.INVISIBLE);
			((Button) findViewById(R.id.btnGenerateMessage))
					.setVisibility(Button.INVISIBLE);
			MainActivity.EVENT_TYPE = MainActivity.TYPE_OWN;
		} else if ((item.getTitle() == "Weihnachten")
				|| (item.getTitle() == "Sylvester")
				|| (item.getTitle() == "Geburtstag")) {
			((Button) findViewById(R.id.btnGenerateMessage))
					.setVisibility(Button.VISIBLE);
			((Button) findViewById(R.id.buttonCreateEventTime))
					.setVisibility(TextView.INVISIBLE);
			((Button) findViewById(R.id.buttonOpenDatePicker))
					.setVisibility(Button.INVISIBLE);
			((TextView) findViewById(R.id.textView2))
					.setVisibility(Button.INVISIBLE);
			((TextView) findViewById(R.id.textView3))
					.setVisibility(Button.INVISIBLE);
			((TextView) findViewById(R.id.textView4))
					.setVisibility(Button.INVISIBLE);
			((Button) findViewById(R.id.btnChooseContacts))
					.setVisibility(Button.VISIBLE);
			MainActivity.EVENT_TYPE = (item.getTitle() == "Weihnachten") ? MainActivity.TYPE_CHRISTMAS
					: (item.getTitle() == "Sylvester" ? TYPE_NEWYEAREVE
							: MainActivity.TYPE_BIRTHDAY);

			((EditText) findViewById(R.id.txtCreateEventPhonenumber))
					.setVisibility(EditText.INVISIBLE);
		} else {
			Toast.makeText(this, "Nothing", Toast.LENGTH_SHORT).show();
			return false;
		}

		return true;
	}

	/**
	 * 
	 */
	private void save() {
		EventsDataSource model = new EventsDataSource(
				this.getApplicationContext());
		ScheduledEvent enteredEvent = getEnteredEvent();
		model.createEvent(enteredEvent);

		Log.d(TAG, "Entered Date " + enteredEvent.getDate().getTime());

		ScheduledEvent nextEvent = model.getNextEvent();
		Utilities.setAlarm(this.getApplicationContext(), nextEvent);
		model.close();
	}

	/**
	 * 
	 * @return
	 */
	private ScheduledEvent getEnteredEvent() {
		final EditText txtMessage = (EditText) findViewById(R.id.txtCreateEventMessage);
		final EditText txtPhoneNumber = (EditText) findViewById(R.id.txtCreateEventPhonenumber);

		final ScheduledEvent scheduledEvent = new ScheduledEvent();
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, dayOfMonth, hourOfDay, minute);
		final Date createDate = cal.getTime();

		scheduledEvent.setDate(createDate);
		scheduledEvent.setMessage(txtMessage.getText().toString());
		scheduledEvent.setPhoneNumber(txtPhoneNumber.getText().toString());
		scheduledEvent.setSent(0);
		return scheduledEvent;
	}

	private static String pad(int c) {
		if (c >= 10) {
			return String.valueOf(c);
		} else {
			return "0" + String.valueOf(c);
		}
	}

	protected void setDayOfMonth(int dayOfMonth) {
		this.dayOfMonth = dayOfMonth;
	}

	protected void setMonth(int month) {
		this.month = month;
	}

	protected void setYear(int year) {
		this.year = year;
	}

	protected void setMinute(int minute) {
		this.minute = minute;
	}

	protected void setHourOfDay(int hourOfDay) {
		this.hourOfDay = hourOfDay;
	}

	@Override
	public void onClick(View v) {
		if (v == this.chooseContactsButton) {
			Intent intent = new Intent(MainActivity.this,
					SelectContactsActivity.class);
			startActivityForResult(intent, REQUEST_CODE);
		} else if (v == this.selectEventTypeButton) {
			registerForContextMenu(v);
			openContextMenu(v);
		} else if (v == generateMessage) {
			generateEventMessage();
		} else if (v == cancelButton) {
			finish();
		} else if (v == save) {
			save();
		}

	}

}
